﻿using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using com.flajaxian.CrmDisService;

namespace com.flajaxian
{
    public class IFDConnection
    {
        // A CrmService reference.
        public readonly CrmService CrmService = null;

        // URL of the Web application.
        public readonly string WebApplicationUrl = String.Empty;

        // GUID of the user's organization.
        public readonly Guid OrganizationId = Guid.Empty;

        /// <summary>
        /// Authenticate the user using IFD (Internet Facing Deployment). The class
        /// constructor sets the values of the public variables (CrmService, etc).
        /// </summary>
        /// <param name="organization">Name of the user's organization.</param>
        /// <param name="server">Microsoft Dynamics CRM server URL.
        /// For example: https://myserver.</param>
        /// <param name="domain">Name of the domain hosting the user's system
        /// account.</param>
        /// <param name="username">User's system account name.</param>
        /// <param name="password">User's account password.</param>
        public IFDConnection(string organization, string server, string domain,
                             string username, string password)
        {
            //Remove any trailing forward slash from the end of the server URL.
            server = server.TrimEnd(new char[] { '/' });

            // Initialize an instance of the CrmDiscoveryService Web service proxy.
            CrmDiscoveryService disco = new CrmDiscoveryService();
            disco.Url = server + "/MSCRMServices/2007/SPLA/CrmDiscoveryService.asmx";

            //Retrieve a list of available organizations.
            RetrieveOrganizationsRequest orgRequest =
                new RetrieveOrganizationsRequest();
            orgRequest.UserId = domain + "\\" + username;
            orgRequest.Password = password;
            RetrieveOrganizationsResponse orgResponse =
                (RetrieveOrganizationsResponse)disco.Execute(orgRequest);

            //Find the desired organization.
            foreach (OrganizationDetail orgdetail in orgResponse.OrganizationDetails)
            {
                if (orgdetail.OrganizationName == organization)
                {
                    //Retrieve the ticket.
                    RetrieveCrmTicketRequest ticketRequest =
                        new RetrieveCrmTicketRequest();
                    ticketRequest.OrganizationName = organization;
                    ticketRequest.UserId = domain + "\\" + username;
                    ticketRequest.Password = password;
                    RetrieveCrmTicketResponse ticketResponse =
                        (RetrieveCrmTicketResponse)disco.Execute(ticketRequest);

                    //Create the CrmService Web service proxy.
                    CrmAuthenticationToken sdktoken = new CrmAuthenticationToken();
                    sdktoken.AuthenticationType = 2;
                    sdktoken.OrganizationName = organization;
                    sdktoken.CrmTicket = ticketResponse.CrmTicket;

                    CrmService = new CrmService();
                    CrmService.CrmAuthenticationTokenValue = sdktoken;
                    CrmService.Url = orgdetail.CrmServiceUrl;

                    WebApplicationUrl = orgdetail.WebApplicationUrl;
                    OrganizationId = orgdetail.OrganizationId;

                    break;
                }
            }
        }
    }
}